# from flask import Flask, request, jsonify, render_template
# from flask_sqlalchemy import SQLAlchemy
# from flask_restful import Api, Resource
# import hashlib
# import xmltodict
# import time
# import json
# from datetime import datetime, timezone
#
# app = Flask(__name__)
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost:3306/chiibug'
# #'sqlite:///data.db'
# #jdbc:mysql://localhost:3306/chiibug
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#
# # 微信公众号配置
# WECHAT_TOKEN = "wyt0206"
#
# db = SQLAlchemy(app)
# api = Api(app)
#
# @app.route('/')
# def index():
#     return "Welcome to WeChat Backend!"
# # 获取UTC时间的函数
# def get_utc_now():
#     return datetime.now(timezone.utc)
#
# # 用户模型
# class User(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     openid = db.Column(db.String(80), unique=True, nullable=False)
#     role = db.Column(db.String(20), default='user')  # user, admin, crawler
#     created_at = db.Column(db.DateTime, default=get_utc_now)  # 修改这里
#
# # 职位信息模型
# class Item(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     name = db.Column(db.String(80), nullable=False)
#     description = db.Column(db.String(200))
#     company = db.Column(db.String(80))
#     salary = db.Column(db.String(50))
#     created_at = db.Column(db.DateTime, default=get_utc_now)  # 修改这里
# created_by = db.Column(db.String(80), db.ForeignKey('user.openid'))
#
# # 用户权限检查
# def check_user_permission(openid, action):
#     user = User.query.filter_by(openid=openid).first()
#     if not user:
#         user = User(openid=openid, role='user')
#         db.session.add(user)
#         db.session.commit()
#
#     if action == 'create' and user.role != 'admin':
#         return False
#     if action == 'read' and user.role == 'crawler':
#         return False
#     return True
#
# # 处理微信消息的函数
# def handle_wechat_message(xml_dict):
#     msg_type = xml_dict['xml']['MsgType']
#     from_user = xml_dict['xml']['FromUserName']
#     to_user = xml_dict['xml']['ToUserName']
#
#     if msg_type == 'text':
#         content = xml_dict['xml']['Content'].strip()
#
#         # 检查用户权限
#         if not check_user_permission(from_user, 'read'):
#             return create_reply(to_user, from_user, "您没有权限访问此信息")
#
#         # 处理各种命令
#         if content.startswith('搜索'):
#             return handle_search(content, to_user, from_user)
#         elif content.startswith('页'):
#             return handle_pagination(content, to_user, from_user)
#         elif content == '帮助':
#             return create_help_message(to_user, from_user)
#         elif content.startswith('添加'):
#             return handle_create(content, to_user, from_user)
#         elif content.startswith('更新'):
#             return handle_update(content, to_user, from_user)
#         elif content.startswith('删除'):
#             return handle_delete(content, to_user, from_user)
#         else:
#             return create_help_message(to_user, from_user)
#
# def handle_search(content, to_user, from_user):
#     search_term = content.replace('搜索', '').strip()
#     page = 1
#     per_page = 5
#
#     query = Item.query.filter(Item.name.contains(search_term) |
#                               Item.company.contains(search_term))
#     pagination = query.paginate(page=page, per_page=per_page)
#
#     if pagination.items:
#         result = f"搜索结果 (第{page}页，共{pagination.pages}页)：\n\n"
#         result += '\n'.join([
#             f"ID: {item.id}\n公司: {item.company}\n职位: {item.name}\n薪资: {item.salary}\n描述: {item.description}\n"
#             for item in pagination.items
#         ])
#         result += f"\n\n发送'页 {search_term} 页码'查看其他页"  # 修改这里，使用单引号
#     else:
#         result = f"未找到与'{search_term}'相关的职位信息"
#
#     return create_reply(to_user, from_user, result)
#
# def handle_pagination(content, to_user, from_user):
#     parts = content.split()
#     if len(parts) >= 3:
#         search_term = parts[1]
#         try:
#             page = int(parts[2])
#             per_page = 5
#
#             query = Item.query.filter(Item.name.contains(search_term) |
#                                       Item.company.contains(search_term))
#             pagination = query.paginate(page=page, per_page=per_page)
#
#             if pagination.items:
#                 result = f"搜索结果 (第{page}页，共{pagination.pages}页)：\n\n"
#                 result += '\n'.join([
#                     f"ID: {item.id}\n公司: {item.company}\n职位: {item.name}\n薪资: {item.salary}\n描述: {item.description}\n"
#                     for item in pagination.items
#                 ])
#                 result += f"\n\n发送'页 {search_term} 页码'查看其他页"  # 修改这里，使用单引号
#             else:
#                 result = "没有更多结果"
#         except ValueError:
#             result = "页码必须是数字"
#     else:
#         result = "格式错误，正确格式：页 关键词 页码"
#
#     return create_reply(to_user, from_user, result)
# def handle_create(content, to_user, from_user):
#     if not check_user_permission(from_user, 'create'):
#         return create_reply(to_user, from_user, "您没有权限添加职位信息")
#
#     try:
#         # 格式：添加 公司名|职位名|薪资|描述
#         info = content.replace('添加', '').strip().split('|')
#         if len(info) != 4:
#             return create_reply(to_user, from_user, "格式错误，正确格式：添加 公司名|职位名|薪资|描述")
#
#         company, name, salary, description = info
#         item = Item(
#             company=company,
#             name=name,
#             salary=salary,
#             description=description,
#             created_by=from_user
#         )
#         db.session.add(item)
#         db.session.commit()
#         return create_reply(to_user, from_user, "添加成功")
#     except Exception as e:
#         return create_reply(to_user, from_user, f"添加失败：{str(e)}")
#
# def handle_update(content, to_user, from_user):
#     if not check_user_permission(from_user, 'create'):
#         return create_reply(to_user, from_user, "您没有权限更新职位信息")
#
#     try:
#         # 格式：更新 ID|公司名|职位名|薪资|描述
#         info = content.replace('更新', '').strip().split('|')
#         if len(info) != 5:
#             return create_reply(to_user, from_user, "格式错误，正确格式：更新 ID|公司名|职位名|薪资|描述")
#
#         item_id, company, name, salary, description = info
#         item = Item.query.get(int(item_id))
#         if not item:
#             return create_reply(to_user, from_user, "未找到指定ID的职位信息")
#
#         item.company = company
#         item.name = name
#         item.salary = salary
#         item.description = description
#         db.session.commit()
#         return create_reply(to_user, from_user, "更新成功")
#     except Exception as e:
#         return create_reply(to_user, from_user, f"更新失败：{str(e)}")
#
# def handle_delete(content, to_user, from_user):
#     if not check_user_permission(from_user, 'create'):
#         return create_reply(to_user, from_user, "您没有权限删除职位信息")
#
#     try:
#         # 格式：删除 ID
#         item_id = content.replace('删除', '').strip()
#         item = Item.query.get(int(item_id))
#         if not item:
#             return create_reply(to_user, from_user, "未找到指定ID的职位信息")
#
#         db.session.delete(item)
#         db.session.commit()
#         return create_reply(to_user, from_user, "删除成功")
#     except Exception as e:
#         return create_reply(to_user, from_user, f"删除失败：{str(e)}")
#
# @app.route('/wechat', methods=['GET', 'POST'])
# def wechat():
#     print(f"Received {request.method} request to /wechat")
#     print(f"Headers: {dict(request.headers)}")
#     print(f"Args: {dict(request.args)}")
#     print(f"Data: {request.data}")
#
#     if request.method == 'GET':
#         # 打印所有参数，用于调试
#         print("GET parameters:", request.args)
#
#         signature = request.args.get('signature', '')
#         timestamp = request.args.get('timestamp', '')
#         nonce = request.args.get('nonce', '')
#         echostr = request.args.get('echostr', '')
#
#         # 如果是普通浏览器访问，返回提示信息
#         if not signature and not timestamp and not nonce:
#             return "This is a WeChat server interface. Please access through WeChat."
#
#         # 验证签名
#         token = WECHAT_TOKEN
#         temp_list = [token, timestamp, nonce]
#         temp_list.sort()
#         temp_str = ''.join(temp_list)
#         hash_obj = hashlib.sha1(temp_str.encode('utf-8'))
#
#         print(f"Token: {token}")
#         print(f"Timestamp: {timestamp}")
#         print(f"Nonce: {nonce}")
#         print(f"Signature: {signature}")
#         print(f"Calculated: {hash_obj.hexdigest()}")
#
#         if hash_obj.hexdigest() == signature:
#             return echostr
#         return f'Invalid signature. Expected {signature}, got {hash_obj.hexdigest()}'
#
#     elif request.method == 'POST':
#         try:
#             xml_data = request.data
#             print(f"Received XML: {xml_data}")
#
#             if not xml_data:
#                 return "Empty request body"
#
#             xml_dict = xmltodict.parse(xml_data)
#             print(f"Parsed dict: {xml_dict}")
#
#             msg_type = xml_dict['xml']['MsgType']
#             from_user = xml_dict['xml']['FromUserName']
#             to_user = xml_dict['xml']['ToUserName']
#
#             if msg_type == 'text':
#                 content = xml_dict['xml']['Content'].strip()
#                 reply_content = "收到消息：" + content
#
#                 if content == '帮助':
#                     reply_content = """支持的命令：
# 1. 搜索 关键词 - 搜索职位信息
# 2. 页 关键词 页码 - 查看搜索结果的其他页
# 3. 添加 公司名|职位名|薪资|描述 - 添加新职位
# 4. 更新 ID|公司名|职位名|薪资|描述 - 更新职位信息
# 5. 删除 ID - 删除职位信息
# 6. 帮助 - 显示此帮助信息"""
#                 elif content == '测试':
#                     reply_content = "系统正常运行中！"
#
#                 reply = {
#                     'xml': {
#                         'ToUserName': from_user,
#                         'FromUserName': to_user,
#                         'CreateTime': int(time.time()),
#                         'MsgType': 'text',
#                         'Content': reply_content
#                     }
#                 }
#
#                 response_xml = xmltodict.unparse(reply)
#                 print(f"Sending response: {response_xml}")
#                 return response_xml
#
#         except Exception as e:
#             print(f"Error processing message: {str(e)}")
#             return str(e)
#
#     return 'OK'
#
# if __name__ == '__main__':
#     # with app.app_context():
#     #     db.create_all()
#     app.run(debug=True, port=8080)